import board
import digitalio
import time

from rich.live import Live
from rich.table import Table

LEFT_FOOT_PIN = board.D5
RIGHT_FOOT_PIN = board.D6

class FeetContacts:
    def __init__(self, render_live_table=False):
        self.left_foot = digitalio.DigitalInOut(LEFT_FOOT_PIN)
        self.left_foot.direction = digitalio.Direction.INPUT
        self.left_foot.pull = digitalio.Pull.UP

        self.right_foot = digitalio.DigitalInOut(RIGHT_FOOT_PIN)
        self.right_foot.direction = digitalio.Direction.INPUT
        self.right_foot.pull = digitalio.Pull.UP

        self.render_live_table = render_live_table
        if self.render_live_table:
            self.live_table = Live(refresh_per_second=30)
            self.live_table.start()

    def get(self):
        left_level = self.left_foot.value
        left_logic = not left_level

        right_level = self.right_foot.value
        right_logic = not right_level

        if self.render_live_table:
            table = Table(title = 'Feet Contacts Data', show_header=True, show_lines=True)

            table.add_column('', width = 8)
            table.add_column('Left Foot', width = 15, style="blue")
            table.add_column('Right Foot', width = 15, style="yellow")

            table.add_row('Level', f"{left_level:.3f}", f"{right_level:.3f}")
            table.add_row('Logic', str(left_logic), str(right_logic))

            self.live_table.update(table)

        return [left_logic, right_logic]

    def stop(self):
        self.left_foot.deinit()
        self.right_foot.deinit()
        if self.render_live_table: self.live_table.stop()

if __name__ == "__main__":
    from keyboard_utils import is_any_key_pressed

    feet_contacts = FeetContacts(render_live_table=True)
    try:
        while True:
            feet_contacts.get()

            if is_any_key_pressed(['\x1b', 'q']):
                break

            time.sleep(0.05)
    finally:
        feet_contacts.stop()
